package com.shopmall.common.jwt;


import com.shopmall.system.dao.MenuMapper;
import com.shopmall.system.entity.Menu;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.function.Supplier;

@Component
public class AuthorizationManager implements org.springframework.security.authorization.AuthorizationManager<RequestAuthorizationContext>
{
    @Resource
    MenuMapper menuMapper;

    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        HttpServletRequest request = object.getRequest();
        // 获取当前正在访问的url
        String uri = request.getRequestURI();

//        List<Menu> menuList = menuMapper.getAllMenus();
//        for (Menu menu : menuList) {
//            String pattern = menu.getPath();
//            if(pattern==null) continue;
//            if (pathMatcher.match(pattern, uri)) {
//                // 获取访问当前菜单需要的角色
//                List<Role> roles = menu.getRoles();
//                // 获取当前用户有哪些角色
//                Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();
//                for (Role role : roles) {
//                    for (GrantedAuthority authority : authorities) {
//                        if (authority.getAuthority().equals(role.getName())) {
//                            return new AuthorizationDecision(true);
//                        }
//                    }
//                }
//                return new AuthorizationDecision(false);
//            }
//        }

        return new AuthorizationDecision(true);
    }
}
